#include "myhead.h"

/* --------------- main --------------- */
int main() 
{
    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == -1) { perror("socket"); exit(1); }

    int opt = 1;
    //设置端口取消绑定限制
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = INADDR_ANY,
        .sin_port = htons(10000)
    };
    if (bind(listenfd, (struct sockaddr *)&addr, sizeof(addr)) == -1 ||
        listen(listenfd, 12) == -1) {
        perror("bind/listen"); exit(1);
    }

    /* 启动管理员线程 */
    pthread_t admin_tid;
    pthread_create(&admin_tid, NULL, admin_thread, NULL);
    pthread_detach(admin_tid);

    //搞一个线程重复刷新
    // pthread_t client_tid;
    // pthread_create(&client_tid, NULL, tr_client, NULL);
    // pthread_detach(client_tid);

    /* 主线程只负责 accept */
    while (1) {
        struct sockaddr_in caddr;
        socklen_t len = sizeof(caddr);
        int connfd = accept(listenfd, (struct sockaddr *)&caddr, &len);
        if (connfd == -1) { perror("accept"); continue; }

        char ip[INET_ADDRSTRLEN];
        //strcpy(ip,inet_ntoa(caddr.sin_addr));//只可以ipv4,不用
        inet_ntop(AF_INET, &caddr.sin_addr, ip, sizeof(ip));//inet_ntoa(struct in_addr in)
        int port = ntohs(caddr.sin_port);
        list_add(connfd, ip, port);
        //pthread_cond_signal(&g_list_con);
        flag = 1;
        printf("新连接 fd=%d %s:%d\n", connfd, ip, port);

        int *pfd = malloc(sizeof(int));
        *pfd = connfd;
        pthread_t tid;
        pthread_create(&tid, NULL, client_thread, pfd);
        pthread_detach(tid);
    }
    //循环内不要随便创建，考虑多个线程创造
    return 0;
}